package cn.shuangliang.contract.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import jdk.nashorn.internal.runtime.JSONFunctions;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Random;

@WebServlet(name = "MainServlet", value = "*.do")
public class MainServlet extends HttpServlet {
    private TypeController t = new TypeController();
    private AdminController admin = new AdminController();
    private ContractController c = new ContractController();
    private ProductController p = new ProductController();
    private HistoryController h = new HistoryController();

    //请求地址分成两部分
    //表示控制器，第二部分是请求地址，中间有-隔开，
    //用反射访问
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获得请求地址：
        String path = request.getServletPath();
        //去掉开头的/ 和结尾的  .do
        path = path.substring(1, path.length() - 3);
        if (path.equals("service") || path.equals("doGet") || path.equals("doPost")) {
            response.sendError(500, "禁止访问此地址！");
            return;
        }
//        if (request.getSession().getAttribute("ADMIN_LOGIN") == null) {
//            if (!path.equals("admin-login") && !path.equals("captcha")) {
//                request.setAttribute("msg", "您还没有登录");
//                request.getRequestDispatcher("/login.html").forward(request, response);
//                return;
//            }
//        }
        //path就是方法名，参数是固定的request和response
        try {
            String[] ar = path.split("-");
            if (ar.length == 1) {
                Method method = this.getClass().getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this, request, response);//调用
                return;
            }
            String controller = ar[0];
            String method = ar[1];
            Field field = this.getClass().getDeclaredField(controller);
            //field.setAccessible(true);//取消私有的限制
            Object obj = field.get(this);//拿到了属性
            Method m = obj.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            Object rtn = m.invoke(obj, request, response);
            if (rtn != null && rtn instanceof String) {
                request.getRequestDispatcher((String) rtn).forward(request, response);
                return;
            }
            if (rtn != null) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONStringWithDateFormat(rtn, "yyyy-MM-dd", SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNonStringValueAsString));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(501, "出错了，信息是：" + e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    //验证码（后台生成一张图)
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.reset();
        int width = 80;
        int height = 40;
        int lines = 10;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = img.getGraphics();

        //设置背景色
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);//画背景
        //填充指定的矩形。使用图形上下文的当前颜色填充该矩形

        //设置字体
        g.setFont(new Font("宋体", Font.BOLD, 18));

        //随机数字
        String str = "";

        Random r = new Random(System.currentTimeMillis());
        for (int i = 0; i < 4; i++) {
            int a = r.nextInt(10);//取10以内的整数[0，9]
            str += a;
            int y = 10 + r.nextInt(20); //10~30范围内的一个整数，作为y坐标
            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawString("" + a, 5 + i * width / 4, y);
        }
        //干扰线
        for (int i = 0; i < lines; i++) {
            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        request.getSession().setAttribute("vcode", str);
        g.dispose();//类似于流中的close()带动flush()---把数据刷到img对象当中
        ImageIO.write(img, "JPG", response.getOutputStream());

    }

}
